<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, 
  Present, 
  Picture, 
  ChatDotRound,
  User
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 基本数据
const loading = ref(true)
const room = ref<any>(null)
const messages = ref<any[]>([])
const inputText = ref('')
const messagesContainer = ref<HTMLElement>()
const imageInput = ref<HTMLInputElement | null>(null)
const uploadingImage = ref(false)

// 礼物相关
const showGiftPanel = ref(false)
const gifts = ref<any[]>([])
const selectedGift = ref<any>(null)
const giftQuantity = ref(1)
const chatRoomUsers = ref<any[]>([])
const selectedReceiver = ref<any>(null)
const sendingGift = ref(false)

// SSE连接
let es: EventSource | null = null

// 计算属性
const isAdmin = computed(() => authStore.isAdmin)
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

onMounted(async () => {
  await fetchRoom()
  await fetchMessages()
  await fetchGifts()
  connectSSE()
  scrollToBottom()
})

onUnmounted(() => {
  if (es) {
    es.close()
    es = null
  }
})

// 채팅방 정보 가져오기
async function fetchRoom() {
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}`)
    room.value = res.data
  } catch (error) {
    ElMessage.error('채팅방 정보 가져오기 실패')
    router.back()
  } finally {
    loading.value = false
  }
}

// 이전 메시지 가져오기
async function fetchMessages() {
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}/history?limit=50`)
    messages.value = res.data.messages || []
    scrollToBottom()
  } catch (error) {
    console.error('이전 메시지 가져오기 실패:', error)
  }
}

// 선물 목록 가져오기
async function fetchGifts() {
  try {
    const res = await request.get('/api/chat/gifts')
    gifts.value = res.data || []
  } catch (error) {
    console.error('선물 목록 가져오기 실패:', error)
  }
}

// 채팅방 사용자 목록 가져오기
async function fetchChatRoomUsers() {
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}/users`)
    chatRoomUsers.value = res.data || []
  } catch (error) {
    console.error('채팅방 사용자 목록 가져오기 실패:', error)
  }
}

// SSE 연결
function connectSSE() {
  const sseUrl = `${API_BASE_URL}/api/chat/rooms/${route.params.id}/stream`
  console.log('移动端连接SSE:', sseUrl)

  es = new EventSource(sseUrl)

  es.addEventListener('open', () => {
    console.log('移动端SSE连接已建立')
  })

  es.addEventListener('error', (error) => {
    console.error('移动端SSE连接错误:', error)
  })

  es.addEventListener('message', (ev) => {
    console.log('移动端收到消息事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
  })

  es.addEventListener('gift', (ev) => {
    console.log('移动端收到礼物事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
    // 移动端也可以看到礼物特效
    try {
      const preset = data.giftEffectPreset || 'burst'
      import('@/utils/useGiftEffects').then((m) =>
        m.useGiftEffects().trigger(preset, Number(data.quantity || 1)),
      )
    } catch (error) {
      console.error('移动端礼物特效失败:', error)
    }
  })

  es.addEventListener('system', (ev) => {
    console.log('移动端收到系统事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
  })
}

// 添加消息到列表
function pushMessage(data: any) {
  messages.value.push({
    id: data.id || Date.now(),
    content: data.content,
    messageType: data.messageType || 'text',
    imageUrl: data.imageUrl,
    username: data.username,
    avatar: data.avatar,
    timestamp: new Date(data.timestamp),
    senderUserId: data.senderUserId,
    isSystem: data.isSystem,
    isGift: data.isGift
  })

  // 保持消息列表不超过100条
  if (messages.value.length > 100) {
    messages.value = messages.value.slice(-100)
  }

  scrollToBottom()
}

// 发送消息
async function sendMessage() {
  const text = inputText.value.trim()
  if (!text) return

  console.log('移动端发送消息:', text)
  try {
    const response = await request.post(`/api/admin/chat-rooms/${route.params.id}/messages`, {
      content: text,
      isSystem: false
    })
    console.log('移动端消息发送响应:', response)
    inputText.value = ''
    ElMessage.success('메시지 발송 성공')
  } catch (error: any) {
    console.error('移动端发送消息失败:', error)
    ElMessage.error(error.response?.data?.error || '메시지 발송 실패')
  }
}

// 选择图片
function selectImage() {
  imageInput.value?.click()
}

// 处理图片选择
async function handleImageSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('이미지 파일을 선택해주세요')
    return
  }

  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('이미지 파일은 10MB를 초과할 수 없습니다')
    return
  }

  uploadingImage.value = true
  try {
    // 上传图片
    const formData = new FormData()
    formData.append('image', file)

    const uploadResponse = await request.post('/api/admin/uploads/chat-image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    console.log('移动端图片上传成功:', uploadResponse)

    // 发送图片消息
    const messageResponse = await request.post(`/api/admin/chat-rooms/${route.params.id}/messages`, {
      messageType: 'image',
      imageUrl: uploadResponse.data.imageUrl,
      isSystem: false
    })

    console.log('移动端图片消息发送成功:', messageResponse)
    ElMessage.success('이미지 발송 성공')
  } catch (error: any) {
    console.error('移动端发送图片失败:', error)
    ElMessage.error(error.response?.data?.error || '이미지 발송 실패')
  } finally {
    uploadingImage.value = false
    // 清空文件选择
    if (target) target.value = ''
  }
}

// 预览图片
function previewImage(imageUrl: string) {
  window.open(imageUrl, '_blank')
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 时间格式
function formatTime(date: Date | string) {
  const d = typeof date === 'string' ? new Date(date) : date
  return d.toLocaleTimeString('ko-KR', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 채팅방 관리로 돌아가기
function goBack() {
  router.push('/chat-rooms')
}

// 打开礼物面板
async function openGiftPanel() {
  showGiftPanel.value = true
  await fetchChatRoomUsers()
}

// 选择礼物
function selectGift(gift: any) {
  selectedGift.value = gift
}

// 选择收礼人
function selectReceiver(user: any) {
  selectedReceiver.value = user
}

// 发送礼物
async function sendGift() {
  if (!selectedGift.value || !selectedReceiver.value) {
    ElMessage.warning('선물과 받을 사람을 선택해주세요')
    return
  }

  console.log('移动端发送礼物:', {
    giftId: selectedGift.value.id,
    giftName: selectedGift.value.name,
    quantity: giftQuantity.value,
    receiverUserId: selectedReceiver.value.id,
    receiverName: selectedReceiver.value.nickname || selectedReceiver.value.name
  })

  sendingGift.value = true
  try {
    await request.post(`/api/admin/chat-rooms/${route.params.id}/gifts`, {
      giftId: selectedGift.value.id,
      quantity: giftQuantity.value,
      receiverUserId: selectedReceiver.value.id
    })
    ElMessage.success('선물 발송 성공')
    showGiftPanel.value = false
    selectedGift.value = null
    selectedReceiver.value = null
    giftQuantity.value = 1
  } catch (error: any) {
    console.error('移动端发送礼物失败:', error)
    ElMessage.error(error.response?.data?.error || '선물 발송 실패')
  } finally {
    sendingGift.value = false
  }
}
</script>

<template>
  <div class="mobile-chat-room" v-if="!loading && room">
    <!-- 移动端头部 -->
    <div class="mobile-header">
      <el-button :icon="ArrowLeft" circle size="small" @click="goBack" />
      <div class="header-info">
        <h2 class="room-title">{{ room.title || '채팅방' }}</h2>
        <span class="room-status" v-if="room.status">{{ room.status === 'active' ? '활성' : '비활성' }}</span>
      </div>
      <el-button type="primary" :icon="Present" circle size="small" @click="openGiftPanel" />
    </div>

    <!-- 聊天区域 -->
    <div class="mobile-chat-container">
      <!-- 消息列表 -->
      <div ref="messagesContainer" class="mobile-messages">
        <div
          v-for="message in messages"
          :key="message.id"
          class="mobile-message"
          :class="{
            'system-message': message.isSystem,
            'gift-message': message.isGift,
            'admin-message': String(message.senderUserId) === String(authStore.user?.id)
          }"
        >
          <div class="message-avatar">
            <img v-if="message.avatar" :src="message.avatar" :alt="message.username" />
            <el-icon v-else size="24">
              <User />
            </el-icon>
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="username">{{ message.username }}</span>
              <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="message-text">
              <template v-if="message.messageType === 'image' && message.imageUrl">
                <img
                  :src="`${API_BASE_URL}${message.imageUrl}`"
                  :alt="message.content"
                  class="message-image"
                  @click="previewImage(`${API_BASE_URL}${message.imageUrl}`)"
                />
                <div class="image-caption" v-if="message.content">{{ message.content }}</div>
              </template>
              <template v-else>
                {{ message.content }}
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="mobile-input-area">
        <input
          v-model="inputText"
          placeholder="메시지 입력..."
          @keyup.enter="sendMessage"
          class="mobile-message-input"
        />
        <input
          ref="imageInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleImageSelect"
        />
        <el-button
          :icon="Picture"
          circle
          size="small"
          @click="selectImage"
          :loading="uploadingImage"
          title="이미지 발송"
        />
        <el-button
          type="primary"
          @click="sendMessage"
          :disabled="!inputText.trim()"
          size="small"
        >
          발송
        </el-button>
      </div>
    </div>

    <!-- 礼物发送面板 -->
    <el-dialog
      v-model="showGiftPanel"
      title="선물 발송"
      width="95%"
      class="mobile-dialog"
    >
      <div class="mobile-gift-panel">
        <!-- 礼物选择 -->
        <div class="gift-section">
          <h4>선물 선택</h4>
          <div class="gift-grid">
            <div
              v-for="gift in gifts"
              :key="gift.id"
              class="gift-item"
              :class="{ active: selectedGift?.id === gift.id }"
              @click="selectGift(gift)"
            >
              <img :src="`${API_BASE_URL}${gift.imageUrl}`" :alt="gift.name" />
              <div class="gift-name">{{ gift.name }}</div>
              <div class="gift-price">{{ gift.price }}P</div>
            </div>
          </div>
        </div>

        <!-- 收礼人选择 -->
        <div class="receiver-section">
          <h4>받을 사람 선택</h4>
          <div class="receiver-list">
            <div
              v-for="user in chatRoomUsers"
              :key="user.id"
              class="receiver-item"
              :class="{ active: selectedReceiver?.id === user.id }"
              @click="selectReceiver(user)"
            >
              <div class="user-avatar">
                <img v-if="user.avatar" :src="user.avatar" :alt="user.nickname || user.name" />
                <el-icon v-else size="20">
                  <User />
                </el-icon>
              </div>
              <span class="user-name">{{ user.nickname || user.name }}</span>
            </div>
          </div>
        </div>

        <!-- 数量选择 -->
        <div class="quantity-section">
          <h4>수량</h4>
          <el-input-number
            v-model="giftQuantity"
            :min="1"
            :max="999"
            style="width: 100%"
          />
        </div>
      </div>

      <template #footer>
        <div class="mobile-dialog-footer">
          <el-button @click="showGiftPanel = false" size="large">취소</el-button>
          <el-button
            type="primary"
            @click="sendGift"
            :loading="sendingGift"
            :disabled="!selectedGift || !selectedReceiver"
            size="large"
          >
            선물 발송
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 加载状态 -->
  <div v-else class="mobile-loading">
    <el-icon class="loading-icon" size="48">
      <ChatDotRound />
    </el-icon>
    <div class="loading-text">채팅방 로딩 중...</div>
  </div>
</template>

<style scoped>
/* 移动端聊天室主容器 */
.mobile-chat-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

/* 移动端头部 */
.mobile-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  z-index: 1000;
}

.header-info {
  flex: 1;
  text-align: center;
  margin: 0 16px;
}

.room-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  line-height: 1.2;
}

.room-status {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

/* 聊天容器 */
.mobile-chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding-top: 56px; /* 头部高度 */
}

/* 消息列表 */
.mobile-messages {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 16px;
  padding-bottom: 80px; /* 输入区域高度 */
}

/* 移动端消息 */
.mobile-message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.mobile-message.system-message {
  justify-content: center;
}

.mobile-message.system-message .message-content {
  background: var(--el-color-info-light-8);
  color: var(--el-color-info);
  border-radius: 16px;
  padding: 8px 16px;
  font-size: 14px;
  text-align: center;
}

.mobile-message.gift-message .message-content {
  background: linear-gradient(135deg, #ff6b6b, #feca57);
  color: white;
  border-radius: 16px;
  padding: 12px 16px;
}

.mobile-message.admin-message {
  flex-direction: row-reverse;
}

.mobile-message.admin-message .message-content {
  background: var(--el-color-primary);
  color: white;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  flex: 1;
  max-width: 70%;
  background: var(--el-bg-color);
  border-radius: 16px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.username {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.timestamp {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.message-text {
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
}

.message-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.message-image:hover {
  transform: scale(1.02);
}

.image-caption {
  margin-top: 8px;
  font-size: 13px;
  color: var(--el-text-color-regular);
}

/* 输入区域 */
.mobile-input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}

.mobile-message-input {
  flex: 1;
  height: 40px;
  padding: 0 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 20px;
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s ease;
}

.mobile-message-input:focus {
  border-color: var(--el-color-primary);
}

.mobile-message-input::placeholder {
  color: var(--el-text-color-placeholder);
}

/* 礼物面板样式 */
.mobile-gift-panel {
  max-height: 60vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.gift-section,
.receiver-section,
.quantity-section {
  margin-bottom: 24px;
}

.gift-section h4,
.receiver-section h4,
.quantity-section h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 12px 0;
}

.gift-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 12px;
}

.gift-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border: 2px solid var(--el-border-color-lighter);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--el-bg-color);
}

.gift-item:hover {
  border-color: var(--el-color-primary-light-5);
  background: var(--el-color-primary-light-9);
}

.gift-item.active {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-8);
}

.gift-item img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
}

.gift-name {
  font-size: 12px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  text-align: center;
  margin-bottom: 4px;
}

.gift-price {
  font-size: 11px;
  color: var(--el-color-warning);
  font-weight: 600;
}

.receiver-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.receiver-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--el-bg-color);
}

.receiver-item:hover {
  border-color: var(--el-color-primary-light-5);
  background: var(--el-color-primary-light-9);
}

.receiver-item.active {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-8);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

/* 移动端对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-dialog-footer {
  display: flex;
  gap: 12px;
  padding: 16px 0 0 0;
}

.mobile-dialog-footer .el-button {
  flex: 1;
}

/* 加载状态 */
.mobile-loading {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-placeholder);
}

.loading-icon {
  color: var(--el-color-primary);
  margin-bottom: 16px;
  animation: pulse 2s infinite;
}

.loading-text {
  font-size: 16px;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 暗黑模式适配 */
:root.dark .mobile-header {
  background: var(--el-bg-color);
  border-bottom-color: var(--el-border-color);
}

:root.dark .mobile-input-area {
  background: var(--el-bg-color);
  border-top-color: var(--el-border-color);
}

:root.dark .mobile-message-input {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
  color: var(--el-text-color-primary);
}

:root.dark .message-content {
  background: var(--el-bg-color);
}

:root.dark .gift-item {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .receiver-item {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}
</style>
